const HandleDB = require('./handleDB');

const handleDB = new HandleDB();
//全局的调度中心
const _messages = {};

function MessageCenter(ctx) {
  //负责记录创建的房间号
  this.regist = async (roomId, userName) => {
    //判断是否有同名房间
    if(await handleDB.search('room', 'roomId', roomId)) {
      ctx.body = {
      message: '创建房间失败',  
      status: 405,  
      };
      return;
    };
    //在调度中心中创建对应的房间数组
    _messages[roomId] = [];
    //将用户放入房间数组中
    _messages[roomId].push(userName);
    await handleDB.insert('room', 'roomId', roomId);
    ctx.body = {
      message: '创建房间成功', 
      status: 200,
      data: {
        roomId
      }
    }
  }
    
  //将加入房间的用户与房间号绑定
  this.subscribe = async (roomId, userName) => {
    //判断要加入的房间是否存在
    if(typeof _messages[roomId] === 'undefined'){
      ctx.body = {
        message: '未找到此房间', 
        status: 400
      };
      return;
    }
    //判断房间内是否有同名用户
    if(await handleDB.search('roomUser', 'userName', userName)){
      ctx.body = {
        message: '房间内有同名用户，请更改您的用户名', 
        status: 403
      };
      return;
    }
    //将用户存入房间数组
    _messages[roomId].push(userName);
    ctx.body = {
      message: '成功', 
      status: 200
    };
  }

  //删除退出房间的用户
  this.clear = (roomId, userName) => {
    //判断房间是否存在
    if(typeof _messages[roomId] === 'undefined') return;
    const idx =  _messages[roomId].findIndex(ele => ele === userName);
    //移除用户
    _messages[roomId].splice(idx-1, 1);
    if(_messages[roomId].length === 0) {
      delete _messages[roomId];
    }
  }
}

module.exports = MessageCenter;